<?php


namespace App\Console\Commands;

use App\Models\Group;
use App\Models\Order;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

/**
 * 自动通知
 * Class AutoNotify
 * @package App\Console\Commands
 */
class OrderAutoNotify extends Command
{
    protected $signature = 'order:notify';

    protected $client;

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //自动通知
        $this->autoNotify();
        return true;
    }

    public function autoNotify()
    {
        //取外部订单， 并且通知未完成的
        $orders = Order::whereNotNull('out_trade_no')
            ->whereIn('status', [2,3])
            ->where('notify_complete', 0)
            ->get();
        Log::info('需要通知的订单', $orders->toArray());
        $orders->each(function(Order $order){
            try{
                $group = Group::whereAppId($order->uid)->first();
                if($group && $group->callback){
                    $param = [
                        'platform' => 'GGPS',
                        'out_trade_no' => $order->out_trade_no,
                        'status' => $order->status,
                        'escort_receive_time' => $order->escort_receive_time,
                        'escort_finish_time' => $order->escort_finish_time,
                        'escort' => [
                            'name' => $order->escort->realname,
                            'phone' => $order->escort->phone,
                            'avatar' => $order->escort->avatar,
                        ]
                    ];
                    $res = http_post($group->callback, $param);
                    Log::info('通知返回'.$res);
                    $order->notify_times += 1;
                    if($res == 'SUCCESS') {
                        $order->notify_complete = 1;
                    }
                    $order->save();
                }
            }catch (\Exception $e){
                Log::error('自动通知错误：'.$e->getMessage());
                return;
            }
        });
    }
}
